package com.example.survey23.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.survey23.common.lang.QueryPageParam;
import com.example.survey23.common.lang.Result;
import com.example.survey23.entity.Group;
import com.example.survey23.entity.User;
import com.example.survey23.service.GroupService;
import com.example.survey23.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.thymeleaf.util.StringUtils;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 23Group
 * @since 2022-11-05
 */
@RestController
@RequestMapping("/group")
public class GroupController {

    @Autowired
    GroupService groupService;

    @Autowired
    UserService userService;

    @PostMapping("/save")
    public Result save(@RequestBody Group group){ // 保存群组
        groupService.save(group);
        long tennantId = group.getOwnerId(); // 得到租户 id

        // 为租户计费
        User user = userService.getById(tennantId);
        user.setFee(user.getFee() + 1); // 创建一个群组加 1 元
        userService.updateById(user);
        return  Result.succ(group.getId());
    }

    @PostMapping("/listPageGroup")
    public Result listPageGroup(@RequestBody QueryPageParam queryPageParam){ // 前端传过来的值被自动转换为分页对象
        Page<Group> page = new Page<>();
        HashMap param = queryPageParam.getParam();
        page.setCurrent(queryPageParam.getPageNum());
        page.setSize(queryPageParam.getPageSize());
        LambdaQueryWrapper<Group> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(param != null){
            String name = (String) param.get("name");
            if(!StringUtils.isEmpty(name)) {
                lambdaQueryWrapper.like(Group::getGroupName, (String) param.get("name"));
            }
        }
        IPage res = groupService.page(page, lambdaQueryWrapper);
        return Result.succ(res);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Group group){ // 修改群组信息
        return groupService.updateById(group)? Result.succ(null) : Result.fail(null);
    }

    @GetMapping("/delete")
    public Result delete(@RequestParam String id){
        return groupService.removeById(id)? Result.succ(null) : Result.fail(null);
    }


}
